<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="患者" prop="patientId">
        <el-input
          v-model="queryParams.patientId"
          placeholder="请输入患者ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物品名称" prop="itemName">
        <el-input
          v-model="queryParams.itemName"
          placeholder="请输入物品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="记录日期" prop="recordDate">
        <el-date-picker 
          clearable
          v-model="queryParams.recordDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择记录日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="记录时间" prop="recordTime">
        <el-time-picker
          clearable
          v-model="queryParams.recordTime"
          value-format="HH:mm:ss"
          format="HH:mm:ss"
          placeholder="请选择记录时间">
        </el-time-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:records:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:records:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:records:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:records:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="recordsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="记录编号" align="center" prop="recordId" />
      <el-table-column label="患者ID" align="center" prop="patientId" />
      <el-table-column label="患者姓名" align="center">
        <template slot-scope="scope">
          {{ getPatientName(scope.row.patientId) }}
        </template>
      </el-table-column>
      <!-- 移除或隐藏物品编码列 -->
      <!-- <el-table-column label="物品编码" align="center" prop="itemCode" /> -->
      <el-table-column label="物品名称" align="center">
        <template slot-scope="scope">
          {{ getItemName(scope.row.itemCode) }}
        </template>
      </el-table-column>
      <el-table-column label="单位" align="center" prop="unit" />
      <el-table-column label="基础量" align="center" prop="baseAmount" />
      <el-table-column label="剩余量" align="center">
        <template slot-scope="scope">
          {{ scope.row.remainAmount === null ? '0' : scope.row.remainAmount }}
        </template>
      </el-table-column>
      <el-table-column label="水分总量" align="center" prop="waterTotal" />
      <el-table-column label="记录日期" align="center" prop="recordDate" width="180" sortable>
        <template slot-scope="scope">
          <span>{{ scope.row.recordDate }}</span>
        </template>
      </el-table-column>
      <el-table-column label="记录时间" align="center" prop="recordTime" width="180" sortable>
        <template slot-scope="scope">
          <span>{{ scope.row.recordTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:records:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:records:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改患者出入量记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="关联患者" prop="patientId">
          <el-select 
            v-model="form.patientId" 
            placeholder="请选择患者"
            filterable
            clearable
            :disabled="title.includes('修改')"
            :loading="patientLoading">
            <el-option
              v-for="patient in patientsList"
              :key="patient.id"
              :label="`${patient.name}(${patient.phoneNumber})`"
              :value="patient.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="关联物品" prop="itemCode">
          <el-cascader
            v-model="form.itemCode"
            :options="itemsTree"
            :props="itemProps"
            placeholder="请选择物品"
            filterable
            clearable
            :loading="itemLoading"
            @change="handleItemChange">
          </el-cascader>
        </el-form-item>
        <el-form-item label="从物品表自动填充" prop="unit">
          <el-input v-model="form.unit" placeholder="请输入从物品表自动填充" disabled />
        </el-form-item>
        <el-form-item label="每单位含水量" prop="waterContent">
          <el-input 
            v-model="currentWaterContent" 
            placeholder="每单位含水量"
            disabled>
            <template slot="append">ml/单位</template>
          </el-input>
        </el-form-item>
        <el-form-item label="输入基础量" prop="baseAmount">
          <el-input 
            v-model.number="form.baseAmount" 
            placeholder="请输入输入基础量"
            @input="calculateWaterTotal" 
          />
        </el-form-item>
        <el-form-item label="输入剩余量" prop="remainAmount">
          <el-input 
            v-model.number="form.remainAmount" 
            placeholder="请输入输入剩余量"
            @input="calculateWaterTotal" 
          />
        </el-form-item>
        <el-form-item label="计算公式结果" prop="waterTotal">
          <el-input 
            v-model="form.waterTotal" 
            placeholder="计算公式结果"
            disabled 
          />
        </el-form-item>
        <el-form-item label="日期" prop="recordDate">
          <el-date-picker
            clearable
            v-model="form.recordDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择日期"
            :default-value="new Date()">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="时间" prop="recordTime">
          <el-time-picker
            clearable
            v-model="form.recordTime"
            value-format="HH:mm:ss"
            format="HH:mm:ss"
            placeholder="请选择时间"
            :default-value="new Date()">
          </el-time-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRecords, getRecords, delRecords, addRecords, updateRecords } from "@/api/system/records";
import { listPatients } from '@/api/system/records'
import { listItems } from '@/api/system/records'

export default {
  name: "Records",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 患者出入量记录表格数据
      recordsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        recordId: null,
        patientId: null,
        itemCode: null,
        unit: null,
        baseAmount: null,
        remainAmount: null,
        waterTotal: null,
        recordDate: null,
        recordTime: null,
        createdTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        patientId: [
          { required: true, message: '请选择患者', trigger: 'change' }
        ],
        itemCode: [
          { required: true, message: "关联物品表编码不能为空", trigger: "blur" }
        ],
        unit: [
          { required: true, message: '单位不能为空', trigger: 'change' }
        ],
        baseAmount: [
          { required: true, message: '输入基础量不能为空', trigger: 'blur' },
          { type: 'number', message: '基础量必须为数字', trigger: 'blur' },
          { validator: (rule, value, callback) => {
              if (value < this.form.remainAmount) {
                callback(new Error('基础量不能小于剩余量'));
              } else {
                callback();
              }
            }, trigger: 'blur' }
        ],
        remainAmount: [
          { validator: (rule, value, callback) => {
              if (value > this.form.baseAmount) {
                callback(new Error('剩余量不能大于基础量'));
              } else {
                callback();
              }
            }, trigger: 'blur' }
        ],
        waterTotal: [
          { required: true, message: '计算公式结果不能为空', trigger: 'blur' }
        ],
        recordDate: [
          { required: true, message: "日期不能为空", trigger: "blur" }
        ],
        recordTime: [
          { required: true, message: "时间不能为空", trigger: "blur" }
        ],
      },
      // 添加新的数据属性
      patientLoading: false,
      itemLoading: false,
      patientsList: [], // 患者列表
      itemsTree: [], // 物品树形数据
      itemProps: {
        value: 'code',
        label: 'label',
        children: 'children',
        checkStrictly: true,
        emitPath: false
      },
      // 当前选中物品的含水量
      currentWaterContent: 0,
    };
  },
  created() {
    this.getList();
    this.getPatientsList(); // 获取患者列表
    this.getItemsList(); // 获取物品列表
  },
  methods: {
    /** 查询患者出入量记录列表 */
    getList() {
      this.loading = true
      Promise.all([
        // 如果还没有获取患者和物品数据，先获取
        !this.patientsList.length ? this.getPatientsList() : Promise.resolve(),
        !this.itemsTree.length ? this.getItemsList() : Promise.resolve()
      ]).then(() => {
        // 获取记录列表
        listRecords(this.queryParams).then(response => {
          this.recordsList = response.rows
          // 默认按照日期和时间排序，最新的排在前面
          this.recordsList.sort((a, b) => {
            // 先按日期排序
            const dateComparison = new Date(b.recordDate) - new Date(a.recordDate)
            if (dateComparison !== 0) return dateComparison
            
            // 如果日期相同，按时间排序
            return b.recordTime.localeCompare(a.recordTime)
          })
          this.total = response.total
          this.loading = false
        })
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      const now = new Date()
      this.form = {
        recordId: null,
        patientId: null,
        itemCode: null,
        unit: null,
        baseAmount: null,
        remainAmount: null,
        waterTotal: null,
        recordDate: now.toISOString().split('T')[0], // 默认当前日期 YYYY-MM-DD
        recordTime: now.toTimeString().slice(0, 8), // 默认当前时间 HH:mm:ss
        createdTime: null
      }
      this.currentWaterContent = 0
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.recordId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加患者出入量记录'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const recordId = row.recordId || this.ids
      getRecords(recordId).then(response => {
        this.form = response.data;
        // 获取当前物品的含水量
        this.setWaterContentByItemCode(this.form.itemCode);
        // 计算水分总量
        this.calculateWaterTotal();
        this.open = true;
        this.title = "修改患者出入量记录";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.recordId != null) {
            updateRecords(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRecords(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const recordIds = row.recordId || this.ids;
      this.$modal.confirm('是否确认删除患者出入量记录编号为"' + recordIds + '"的数据项？').then(function() {
        return delRecords(recordIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/records/export', {
        ...this.queryParams
      }, `records_${new Date().getTime()}.xlsx`)
    },
    // 获取患者列表
    getPatientsList() {
      this.patientLoading = true
      listPatients().then(response => {
        this.patientsList = response.data || [] // 使用 response.data 而不是 rows
        this.patientLoading = false
      }).catch(() => {
        this.patientLoading = false
      })
    },
    // 获取物品列表并转换为树形结构
    getItemsList() {
      this.itemLoading = true
      listItems().then(response => {
        const items = response.data || []
        // 转换为树形结构
        this.itemsTree = this.convertToTree(items)
        this.itemLoading = false
      }).catch(() => {
        this.itemLoading = false
      })
    },
    // 将平铺数据转换为树形结构
    convertToTree(items) {
      const result = []
      const category1Map = new Map()
      
      items.forEach(item => {
        // 第一层分类
        let cat1 = category1Map.get(item.category1)
        if (!cat1) {
          cat1 = {
            label: item.category1,
            code: item.category1,
            children: new Map()
          }
          category1Map.set(item.category1, cat1)
          result.push(cat1)
        }

        // 第二层分类
        let cat2 = cat1.children.get(item.category2)
        if (!cat2) {
          cat2 = {
            label: item.category2,
            code: item.category2,
            children: []
          }
          cat1.children.set(item.category2, cat2)
        }

        // 第三层（具体物品），添加含水量信息到标签中
        cat2.children.push({
          label: `${item.category3} (含水量: ${item.waterContent}ml/单位)`,
          code: item.code,
          unit: item.unit,
          waterContent: item.waterContent
        })
      })

      // 转换 Map 为数组
      result.forEach(cat1 => {
        cat1.children = Array.from(cat1.children.values())
      })

      return result
    },
    // 物品选择变化时的处理
    handleItemChange(value) {
      if (value) {
        const findItem = (items) => {
          for (const item of items) {
            if (item.code === value) {
              return item
            }
            if (item.children) {
              const found = findItem(item.children)
              if (found) return found
            }
          }
          return null
        }

        const selectedItem = findItem(this.itemsTree)
        if (selectedItem) {
          // 自动填充单位和含水量
          this.form.unit = selectedItem.unit
          this.currentWaterContent = selectedItem.waterContent
          // 重新计算结果
          this.calculateWaterTotal()
        }
      } else {
        // 清空选择时清空相关字段
        this.form.unit = ''
        this.currentWaterContent = 0
        this.form.waterTotal = ''
      }
    },
    // 计算水分总量
    calculateWaterTotal() {
      const baseAmount = Number(this.form.baseAmount) || 0
      const remainAmount = Number(this.form.remainAmount) || 0
      
      // 检查基础量是否小于剩余量
      if (baseAmount < remainAmount) {
        this.$message.error('基础量不能小于剩余量');
        this.form.waterTotal = '';
        return;
      }
      
      if (baseAmount >= 0 && this.currentWaterContent > 0) {
        // 计算公式：（基础量-剩余量）* 每单位水分（毫升）
        const result = (baseAmount - remainAmount) * this.currentWaterContent
        this.form.waterTotal = result.toFixed(2)
      } else {
        this.form.waterTotal = ''
      }
    },
    // 获取患者名字
    getPatientName(patientId) {
      const patient = this.patientsList.find(p => p.id === patientId)
      return patient ? `${patient.name}(${patient.phoneNumber})` : ''
    },
    // 获取物品名称（第三类名称）
    getItemName(itemCode) {
      const findItem = (items) => {
        for (const item of items) {
          if (item.code === itemCode) {
            return item.label.split(' (')[0] // 移除含水量信息
          }
          if (item.children) {
            for (const child of item.children) {
              if (child.children) {
                for (const grandChild of child.children) {
                  if (grandChild.code === itemCode) {
                    return grandChild.label.split(' (')[0] // 移除含水量信息
                  }
                }
              }
            }
          }
        }
        return ''
      }
      return findItem(this.itemsTree)
    },
    // 添加新方法：根据物品编码设置含水量
    setWaterContentByItemCode(itemCode) {
      if (!itemCode) return;
      
      const findItemWaterContent = (items) => {
        for (const item of items) {
          if (item.code === itemCode) {
            return item.waterContent;
          }
          if (item.children && item.children.length) {
            for (const child of item.children) {
              if (child.children && child.children.length) {
                for (const grandChild of child.children) {
                  if (grandChild.code === itemCode) {
                    return grandChild.waterContent;
                  }
                }
              }
            }
          }
        }
        return 0;
      };
      
      this.currentWaterContent = findItemWaterContent(this.itemsTree);
    },
  }
};
</script>

<style>
.el-select-dropdown__wrap {
  max-height: none;
}
</style>
